﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Yyyg.BLL;
using Yyyg.Models;
using Yyyg.WebUI.Filter;
using Yyyg.WebUI.Models;

namespace Yyyg.WebUI.Controllers
{
    internal enum BackStageOrder
    {
        None,
        DelGood,
        GetSumPage,
    }
    public class BackStageController : Controller
    {
        public IBLL.IGoodsService GoodsOper { get; set; }


        // GET: BackStage
        public ActionResult Login()
        {
#if DEBUG
            var adm = new AdminVM()
            {
                Mobel = "15672400683",
                Pwd = "123456",
                Name = "浩东"
            };
            this.Session["admin"] = adm;
            return View("HomePage", adm);
#else
            Session["admin"] = null;
            return View();
#endif
        }

        [HttpGet]
        public ActionResult HomePage()
        {
            return RedirectToAction("Login");
        }

        [HttpPost]
        public ActionResult HomePage(AdminVM admin)
        {
            if (!this.ModelState.IsValid) return RedirectToAction("Login");
            if (!BLL.AdminOper.Login(admin.Mobel, admin.Pwd)) return RedirectToAction("Login");
            admin.Name = BLL.AdminOper.GetAdminName(admin.Mobel);
            this.Session.Add("admin", admin);
            return View(admin);
        }

        [AdminLoginCkeckFilter]
        [HttpPost]
        //指令操作接口
        public string Order(int oid, string jsondata = "", string tag = "")
        {
            var order = (BackStageOrder)oid;
            string result = "ok";
            string jdata = string.IsNullOrEmpty(jsondata) ? "" : jsondata;
            switch (order)
            {
                case BackStageOrder.DelGood:
                    string guid = tag;
                    this.DelGoodDir(GoodsOper.QueryGoodByGuid(guid));
                    result = GoodsOper.DelGood(guid).ToString();
                    break;
                case BackStageOrder.GetSumPage:
                    result = GoodsOper.GetSumPages().ToString();
                    break;
                default:
                    break;
            }
            return result;
        }

        //[LoginCkeckFilter]
        [HttpGet]
        //添加商品时访问
        public ActionResult AddGood()
        {
            this.ViewBag.Types = GoodsOper.GetTypes();
            return View(new GoodVM());
        }

        //[LoginCkeckFilter]
        [HttpGet]
        //查看商品时访问
        public ActionResult LookGood(string guid)
        {
            var g = GoodsOper.QueryGoodByGuid(guid);
            if (g == null)
            {
                return View(new GoodVM());
            }
            this.ViewBag.Types = GoodsOper.GetTypes();

            var subs = JsonConvert.DeserializeObject<string[]>(g.Subimgs_url);
            var dets = JsonConvert.DeserializeObject<string[]>(g.Detimgs_url);
            for (int i = 0; i < subs.Length; i++) { subs[i] = "/UpLoaded/Goods/" + g.Guid + "/" + subs[i]; }
            for (int i = 0; i < dets.Length; i++) { dets[i] = "/UpLoaded/Goods/" + g.Guid + "/" + dets[i]; }
            GoodVM gd = new GoodVM();
            gd.SetDefaule = true;
            gd.Title = g.Title;
            gd.Guid = g.Guid;
            gd.Stock = g.Stock;
            gd.Price = (double)g.Price;
            gd.Mainimg_URL = "/UpLoaded/Goods/" + g.Guid + "/" + g.Mainimg_url;
            gd.SubImgs_URL = subs;
            gd.DetImgs_URL = dets;
            gd.Typeid = g.Typeid;
            gd.Brin = g.Brin;
            gd.Enable = g.Enable;
            gd.NeedAmount = g.Need_amo;
            this.Response.Cache.SetExpires(DateTime.Now.AddHours(1));
            return View("AddGood", gd);
        }

        [AdminLoginCkeckFilter]
        [HttpPost]
        //添加数据时访问
        public async Task<string> AddNewGood(GoodVM gd)
        {
            if (this.ModelState.IsValid)
            {
                var guid = Guid.NewGuid().ToString("N");//商品唯一GUID
                var mainImg = gd.Mainimg;
                var subImgs = gd.Subimgs;
                var detImgs = gd.Detimgs;
                string mainImgName = "";
                string subImgsJson = "";
                string detImgsJson = "";
                string dic = this.Server.MapPath("/UpLoaded/Goods/" + guid + "/");
                Directory.CreateDirectory(dic);
                mainImgName = Path.GetFileName(gd.Mainimg[0].SaveGood(this.Server, guid));
                //存储商品附属图片
                if (subImgs.Length > 0)
                {
                    string[] subs = new string[subImgs.Length];
                    for (int i = 0; i < subImgs.Length; i++)
                    {
                        var filebase = subImgs[i];
                        subs[i] = Path.GetFileName(filebase.SaveGood(this.Server, guid));
                    }
                    subImgsJson = JsonConvert.SerializeObject(subs);
                }

                if (detImgs.Length > 0)
                {
                    //存储商品详情图片
                    string[] dets = new string[detImgs.Length];
                    for (int i = 0; i < detImgs.Length; i++)
                    {
                        var filebase = detImgs[i];
                        dets[i] = Path.GetFileName(filebase.SaveGood(this.Server, guid));
                    }
                    detImgsJson = JsonConvert.SerializeObject(dets);
                }
                Goods good = new Goods()
                {
                    Title = gd.Title,
                    Guid = guid,
                    Price = (decimal)gd.Price,
                    Need_amo = gd.NeedAmount,
                    Typeid = gd.Typeid,
                    Stock = gd.Stock,
                    Brin = gd.Brin,
                    Mainimg_url = mainImgName,
                    Detimgs_url = detImgsJson,
                    Subimgs_url = subImgsJson,
                    Enable = gd.Enable
                };
                var rs = GoodsOper.Add(good);

                return JsonConvert.SerializeObject(new
                {
                    isucc = rs,
                    errors = new string[0],
                });
            }
            else
            {
                var res = new
                {
                    issucc = false,
                    errors = this.ModelState.GetErrors()
                };
                return JsonConvert.SerializeObject(res);
            }
        }

        [AdminLoginCkeckFilter]
        [HttpGet]
        //查询数据时访问
        public async Task<ActionResult> QueryGoods(string value = "1", int qtpe = 2)
        {
            /*
             * qtype 约定
             * 1:根据查询框内容查询
             * 2:根据页码查询
             */
            var list = new List<Goods>();
            List<Goods> res = new List<Goods>();
            if (qtpe == 1) res = GoodsOper.QueryGoods(value);
            else res =  GoodsOper.QueryGoodsPage(int.Parse(value));
            this.ViewBag.QueryList = res;
            return View();
        }

        [AdminLoginCkeckFilter]
        [HttpPost]
        public async Task<string> SetGood(GoodVM gd)
        {
            if (gd.Guid.Length == 0) return JsonConvert.SerializeObject(new { isucc = "False", errors = new string[0] });

            var g = GoodsOper.QueryGoodByGuid(gd.Guid);
            g.Title = gd.Title;
            g.Price = (decimal)gd.Price;
            g.Stock = gd.Stock;
            g.Typeid = gd.Typeid;
            g.Enable = gd.Enable;
            await Task.Run(() =>
            {
                #region 图片增删处理
                //展示
                if (gd.Mainimg.Length > 0 && gd.Mainimg[0] != null && gd.Mainimg[0].ContentLength > 0)
                {
                    if (!string.IsNullOrEmpty(g.Mainimg_url))
                    {
                        var fbs = gd.Mainimg[0];
                        var full = this.Server.MapPath(g.GetMainImgPath());
                        if (System.IO.File.Exists(full)) System.IO.File.Delete(full);
                        g.Mainimg_url = fbs.SaveGood(this.Server, gd.Guid);
                    }
                }
                //删除包含的附属图片
                List<string> sublist = JsonConvert.DeserializeObject<List<string>>(g.Subimgs_url);
                var subs = gd.SubDelFiles;
                if (subs != null)
                    for (int i = 0; i < subs.Length; i++)
                    {
                        var full = this.Server.MapPath(subs[i]);
                        if (System.IO.File.Exists(full)) System.IO.File.Delete(full);
                        sublist.Remove(Path.GetFileName(subs[i]));
                    }
                //删除包含的详情图片
                List<string> detlist = JsonConvert.DeserializeObject<List<string>>(g.Detimgs_url);
                var dets = gd.DetDelFiles;
                if (dets != null)
                    for (int i = 0; i < dets.Length; i++)
                    {
                        var full = this.Server.MapPath(dets[i]);
                        if (System.IO.File.Exists(full)) System.IO.File.Delete(full);
                        detlist.Remove(Path.GetFileName(dets[i]));
                    }
                //添加新增的附属图片 
                if (gd.Subimgs != null && gd.Subimgs.Length > 0)
                {
                    for (int i = 0; i < gd.Subimgs.Length; i++)
                    {
                        var file = gd.Subimgs[i];
                        if (file != null && file.ContentLength > 0)
                        {
                            sublist.Add(Path.GetFileName(file.SaveGood(this.Server, g.Guid)));
                        }
                    }
                }
                //添加新增的详情图片
                if (gd.Detimgs != null && gd.Detimgs.Length > 0)
                {
                    for (int i = 0; i < gd.Detimgs.Length; i++)
                    {
                        var file = gd.Detimgs[i];
                        if (file != null && file.ContentLength > 0)
                        {
                            detlist.Add(Path.GetFileName(file.SaveGood(this.Server, g.Guid)));
                        }
                    }
                }
                #endregion
                g.Subimgs_url = JsonConvert.SerializeObject(sublist);
                g.Detimgs_url = JsonConvert.SerializeObject(detlist);
            });
            using (LuckyEntities luck = new LuckyEntities())
            {
                luck.Entry<Goods>(g).State = System.Data.Entity.EntityState.Modified;
                luck.SaveChanges();
            }
            return JsonConvert.SerializeObject(new
            {
                isucc = "True",
                errors = new string[0],
            });
        }

        //删除商品对应路径
        private void DelGoodDir(Goods g)
        {
            string rootdir = ConfigurationManager.AppSettings["GoodImageRootDir"];

            string dir = this.Server.MapPath(rootdir + "/" + g.Guid + "/");

            if (Directory.Exists(dir))
            {
                try
                {
                    Directory.Delete(dir, true);
                }
                catch (Exception ex)
                {

                }
            }
        }
    }

    internal static class Ext
    {
        private static string rootdir = ConfigurationManager.AppSettings["GoodImageRootDir"];

        public static string SaveGood(this HttpPostedFileBase file, HttpServerUtilityBase server, string guid)
        {
            string gu = Guid.NewGuid().ToString("N").Substring(0, 16);
            var ext = Path.GetExtension(file.FileName);
            string filename = gu + ext;
            string fullpath = rootdir + "/" + guid + "/" + filename;
            file.SaveAs(server.MapPath(fullpath));
            return fullpath;
        }

        public static bool RemoveItem(this string[] vs, string value)
        {
            List<string> res = new List<string>(vs);
            var rs = res.Remove(value);
            vs = res.ToArray();
            return rs;
        }
    }
}